package com.jstyle.jclifexd.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.adapter.RankactivityerAdapter;
import com.jstyle.jclifexd.model.Activitities;
import com.jstyle.jclifexd.model.Activitvtiesmsg;
import com.jstyle.jclifexd.model.Createddata;
import com.jstyle.jclifexd.model.RankData;
import com.jstyle.jclifexd.utils.NetWorkConast;
import com.jstyle.jclifexd.utils.RxBus;
import com.jstyle.jclifexd.utils.SchedulersTransformer;

import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 参加活动人员排名
 */

public class ActivityrankingActivity extends BaseActivity {
    @BindView(R.id.title)
    Button title;
    @BindView(R.id.RecyclerView_rank)
    RecyclerView RecyclerView_rank;
    @BindView(R.id.tv_rank_distance)
    TextView tv_rank_distance;
    @BindView(R.id.tv_rank_step)
    TextView tv_rank_step;
    @BindView(R.id.tv_rank_pace)
    TextView tv_rank_pace;
    @BindView(R.id.tv_rank_duration)
    TextView tv_rank_duration;
    @BindView(R.id.bt_exithuodong)
    Button bt_exithuodong;
    RankactivityerAdapter rankactivityAdapter;
    List<TextView> list = new ArrayList<>();
    Createddata activitiesActivity;
    List<RankData.DataBean> listRankData;
    private final int sortType_Distance = 0;
    private final int sortType_Step = 1;
    private final int sortType_Pace = 2;
    private final int sortType_Duration = 3;
    private int sortType = sortType_Distance;
    boolean isCreator = false;//是否是活动的创建者

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rankactivitie);
        ButterKnife.bind(this);
        if (null != getIntent() && null != getIntent().getSerializableExtra("activitiesActivity")) {
            activitiesActivity = (Createddata) getIntent().getSerializableExtra("activitiesActivity");
            getRank(activitiesActivity);
            title.setText(TextUtils.isEmpty(activitiesActivity.getTitle()) ? getResources().getString(R.string.activityranking) : activitiesActivity.getTitle());
            if (NetWorkUtil.getUserId().trim().equals(activitiesActivity.getCreaterUid() + "")) {
                bt_exithuodong.setText(getResources().getString(R.string.cancel_activities));
                isCreator = true;
            }
        }
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        ColorDrawable colorDrawable = new ColorDrawable();
        colorDrawable.setColor(Color.LTGRAY);
        dividerItemDecoration.setDrawable(colorDrawable);
        RecyclerView_rank.addItemDecoration(dividerItemDecoration);
        rankactivityAdapter = new RankactivityerAdapter(this, activitiesActivity.getActId() + "");
        RecyclerView_rank.setLayoutManager(new LinearLayoutManager(this));
        RecyclerView_rank.setAdapter(rankactivityAdapter);

        list.clear();
        list.add(tv_rank_distance);
        list.add(tv_rank_step);
        list.add(tv_rank_pace);
        list.add(tv_rank_duration);
        setSelected(tv_rank_distance);

    }


    @OnClick({R.id.iv_back, R.id.tv_rank_distance, R.id.tv_rank_step,
            R.id.tv_rank_pace, R.id.tv_rank_duration, R.id.bt_exithuodong})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_rank_distance: //距离
                sortType = sortType_Distance;
                setSelected(tv_rank_distance);
                break;
            case R.id.tv_rank_step://步数
                sortType = sortType_Step;
                setSelected(tv_rank_step);
                break;
            case R.id.tv_rank_pace://配速
                sortType = sortType_Pace;
                setSelected(tv_rank_pace);
                break;
            case R.id.tv_rank_duration://时间
                sortType = sortType_Duration;
                setSelected(tv_rank_duration);
                break;
            case R.id.bt_exithuodong://退出活动
                if (!isCreator) {
                    ExitActivities();
                } else {
                    DeleteActivities();
                }

                break;
        }
    }

    private void getRank(Createddata activitiesActivity) {
        Map<String, Object> map = new HashMap<>();
        map.put("actId", activitiesActivity.getActId() + "");
        map.put(NetWorkConast.KEY_uid, NetWorkUtil.getUserId());
        NetWorkUtil.getInstance().getJstyleApi().rank(map)
                .compose(SchedulersTransformer.<RankData>io2MainObservable())
                .subscribe(new Observer<RankData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(RankData netResultData) {
                        List<RankData.DataBean> data = netResultData.getData();
                        listRankData = data;
                        if (sortType != sortType_Distance) {
                            sortData(data);
                        } else {
                            updateData(data);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        String msg=e.getMessage();
                        if(e instanceof ConnectException){
                            msg=getString(R.string.Network_not_availa);
                        }
                        showToast(msg);
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    /**
     * 退出活动
     */
    private void ExitActivities() {
        AlertDialog alertDialog = new AlertDialog.Builder(this, R.style.appalertdialog)
                .setTitle(getString(R.string.tips))
                .setMessage(getResources().getString(R.string.withdrawalactivities))
                .setCancelable(true)
                .setPositiveButton(getString(R.string.Confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("actId", activitiesActivity.getActId() + "");
                        map.put("uid", NetWorkUtil.getUserId());
                        NetWorkUtil.getInstance().getJstyleApi().quit(map).
                                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Activitvtiesmsg>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(Activitvtiesmsg activitvtiesData) {
                                showToast(getResources().getString(R.string.successdrawalteam));
                                RxBus.getInstance().post("reload");
                                finish();
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });
                    }
                })
                .setNegativeButton(getResources().getString(R.string.cancel), null)
                .create();
        alertDialog.show();
    }


    /**
     * 删除活动
     */
    private void DeleteActivities() {
        AlertDialog alertDialog = new AlertDialog.Builder(this, R.style.appalertdialog)
                .setTitle(getString(R.string.tips))
                .setMessage(getResources().getString(R.string.cancel_activities))
                .setCancelable(true)
                .setPositiveButton(getString(R.string.Confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("actId", activitiesActivity.getActId() + "");
                        map.put("uid", NetWorkUtil.getUserId());
                        NetWorkUtil.getInstance().getJstyleApi().deleteactivity(map).
                                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Activitvtiesmsg>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(Activitvtiesmsg activitvtiesData) {
                                showToast(getResources().getString(R.string.submit_successfully));
                                RxBus.getInstance().post("reload");
                                finish();
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });
                    }
                })
                .setNegativeButton(getResources().getString(R.string.cancel), null)
                .create();
        alertDialog.show();
    }


    private void setSelected(TextView textView) {
        for (TextView tv : list) {
            tv.setSelected(textView == tv);
        }
        sortData(listRankData);
    }


    private void sortData(List<RankData.DataBean> listRankData) {
        if (listRankData == null || listRankData.size() == 0) return;
        Collections.sort(listRankData, new Comparator<RankData.DataBean>() {
            @Override
            public int compare(RankData.DataBean o1, RankData.DataBean o2) {
                int result = 0;
                switch (sortType) {
                    case sortType_Distance:
                        result = o2.getDistance() - o1.getDistance() < 0 ? -1 : 1;
                        break;
                    case sortType_Duration:
                        result = o2.getActiveTime() - o1.getActiveTime();
                        break;
                    case sortType_Pace:
                        if (o1.getPace() == 0 || o2.getPace() == 0) {
                            result = 0;
                        } else if (o1.getPace() - o2.getPace() > 0) {
                            return 1;
                        } else {
                            return -1;
                        }
                        break;
                    case sortType_Step:
                        result = o2.getDays() - o1.getDays();
                        break;
                }
                return result;
            }
        });
        updateData(listRankData);
    }


    private void updateData(List<RankData.DataBean> data) {
        if (data == null) data = new ArrayList<>();
        rankactivityAdapter.updateData(data);
    }
}
